package com.example.weixinredpackokhttp.utils;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;

import java.util.concurrent.*;

/**
 * guava事件总线
 *
 * @author shadow
 */
public class EventBusUtil {

    private static EventBus eventBus;
    private static AsyncEventBus asyncEventBus;
    /**
     * 创建线程池
     */
    private static final Executor EXECUTOR = new ThreadPoolExecutor(10, 30,
        30, TimeUnit.SECONDS,
        new LinkedBlockingQueue<>(100),
        new ThreadPoolExecutor.DiscardPolicy());

    private EventBusUtil() {
    }

    //双重锁单例模式
    private static AsyncEventBus getAsynEventBus() {
        if (asyncEventBus == null) {
            synchronized (AsyncEventBus.class) {
                if (asyncEventBus == null) {
                    asyncEventBus = new AsyncEventBus(EXECUTOR);
                }
            }
        }
        return asyncEventBus;
    }

    //双重锁单例模式
    private static EventBus getEventBus() {
        if (eventBus == null) {
            synchronized (EventBus.class) {
                if (eventBus == null) {
                    eventBus = new EventBus();
                }
            }
        }
        return eventBus;
    }

    /**
     * 同步发送事件
     *
     * @param event
     */
    public static void post(Object event) {
        getEventBus().post(event);
    }

    /**
     * 异步方式发送事件
     */
    public static void asyncPost(Object event) {
        getAsynEventBus().post(event);
    }

    /**
     * 注册事件
     * @param event
     */
    public static void register(Object event) {
        getEventBus().register(event);
        getAsynEventBus().register(event);
    }

    /**
     * 取消注册
     * @param event
     */
    public static void unregister(Object event) {
        getEventBus().unregister(event);
        getAsynEventBus().unregister(event);
    }

}
